/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.aspsine.multithreaddownload.demo.util;

import com.aspsine.multithreaddownload.DownloadException;
import com.aspsine.multithreaddownload.architecture.DownloadStatus;
import com.aspsine.multithreaddownload.demo.entity.AppInfo;
import com.aspsine.multithreaddownload.util.IOCloseUtils;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.*;

public class RandomAccessFileContr {
    public static InputStream transferData(InputStream InputStreams, AppInfo info)throws DownloadException{
        final InputStream[] in = {null};
        ThreadPoolUtil.submit(()->{
            try {
                in[0] = transferDatas(InputStreams,info);
            } catch (DownloadException e) {
                e.printStackTrace();
            }
        });
        return in[0];
    }

    public static InputStream transferDatas(InputStream InputStreams, AppInfo info)
            throws DownloadException {
        HiLog.debug(new HiLogLabel(3,0,"XYZ111"),"transferData");
        InputStream inputStream = null;
        RandomAccessFile raf = null;
        HiLog.debug(new HiLogLabel(3,0,"XYZ"),"transferData File= "+Utils.mDownloadDir);
        FileOutputStream outputStream = null;
        byte[] bytes = new byte[1024];
        int len = -1;
        InputStream in = null;
        try {
            try {
                inputStream = InputStreams;
            } catch (Exception e) {
                throw new DownloadException(DownloadStatus.STATUS_FAILED,
                "http get inputStream error", e);
            }
            File imagefile = new File(Utils.mDownloadDir,info.getName()+".jpg");
            try{
                outputStream = new FileOutputStream(imagefile);
                while ((len = inputStream.read(bytes))!=-1){
                    outputStream.write(bytes,0,len);
                }
                outputStream.close();
                bytes.clone();
                inputStream.close();

                in = new FileInputStream(imagefile);
                return in;


            }catch (Exception e){

            }
            try {
              //  File file = new File(dir, name);
               // raf = getFile(Utils.mDownloadDir, info.getName()+".jpg",0);

                HiLog.debug(new HiLogLabel(3,0,"XYZ"),"transferData File= "+raf.toString());
               // HiLog.debug(new HiLogLabel(3,0,"XYZ"),String.format(Locale.ROOT,"% %",raf));
            } catch (Exception e) {
                throw new DownloadException(DownloadStatus.STATUS_FAILED, "File error", e);
            }
           // transferData(inputStream, raf);
        } finally {
            HiLog.debug(new HiLogLabel(3,0,"XYZ"),"transferData File= "+
                    raf.toString()+"input="+inputStream);

            try {
                IOCloseUtils.close(inputStream);
                IOCloseUtils.close(raf);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return in;
    }

    private static void transferData(InputStream inputStream, File file) throws DownloadException {
        final byte[] buffer = new byte[1024 * 8];
        while (true) {
            int len = -1;
            try {
                len = inputStream.read(buffer);
                if (len == -1) {
                    break;
                }
               // raf.write(buffer, 0, len);

            } catch (IOException e) {
                throw new DownloadException(DownloadStatus.STATUS_FAILED, e);
            }
        }
    }

    private static void transferData(InputStream inputStream, RandomAccessFile raf) throws DownloadException {
        final byte[] buffer = new byte[1024 * 8];
        while (true) {
            int len = -1;
            try {
                len = inputStream.read(buffer);
                if (len == -1) {
                    break;
                }
                raf.write(buffer, 0, len);

            } catch (IOException e) {
                throw new DownloadException(DownloadStatus.STATUS_FAILED, e);
            }
        }
    }

    private static RandomAccessFile getFile(File dir, String name, long offset) throws IOException {
        File file = new File(dir, name);
        HiLog.debug(new HiLogLabel(3,0,"XYZ"),"transferData File= "+file);
        RandomAccessFile raf = new RandomAccessFile(file, "rwd");
        HiLog.debug(new HiLogLabel(3,0,"XYZ"),"transferData File1= "+file);
       // if(offset!=0)
        raf.seek(offset);
        return raf;
    }

}
